package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.service.IPermissionService;
import cn.wolfcode.rbac.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper mapper;
    @Autowired
    private IPermissionService permissionService;//登录需要告知系统用户的权限
    @Override
    @Transactional(readOnly = true)
    public void login(String username, String password) {
        //
        Employee emp = mapper.selectByInfo(username, password);
        if(emp==null){
          throw new RuntimeException("用户名和密码不匹配");
        }
        UserContext.setCurrentUser(emp);
        List<String> permission = this.permissionService.selectByEmpId(emp.getId());
        UserContext.setExpression(permission);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> list = this.mapper.selectForList(qo);
        return new PageInfo(list);
    }

    //ids对修改角色使用的。保存角色信息的
    @Override
    public void saveOrUpdate(Employee entity, Long[] ids) {
        System.out.println("entitiy======"+entity);
        if(entity.getId()==null){
            String password = entity.getPassword();
            Md5Hash md5Hash = new Md5Hash(password,entity.getName());
            entity.setPassword(md5Hash.toString());
            this.mapper.insert(entity);
        }else {
            this.mapper.updateByPrimaryKey(entity);
            //对原有角色记录进行删除，更恶心为新的角色
            this.mapper.deleteRelation(entity.getId());
        }
        //对角色修改
        if((ids!=null) && (ids.length>0)){
            for(Long roleId:ids){
                this.mapper.insertRelation(entity.getId(),roleId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        this.mapper.deleteByPrimaryKey(id);
        this.mapper.deleteRelation(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Employee get(Long id) {
        return this.mapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Employee> list() {
        return this.mapper.selectAll();
    }

    @Override
    public void abtchDelete(Long[] ids) {
        this.mapper.deleteBbatch(ids);
    }

    @Override
    public boolean checkName(String name) {
        if(this.mapper.checkName(name)!=null) {
            return false;
        }else {
            return true;
        }
    }

    @Override
    public Workbook exporxls() {
        //创建一个XLS文件
        Workbook wb = new HSSFWorkbook();
        //创建SHEET,给SHEET起名和不起名的实现
        Sheet sheet = wb.createSheet("员工名单");
        //创建行 从0开始
        Row row = sheet.createRow(0);

        //单元格，写表头信息
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询员工数据
        List<Employee> employees = mapper.selectAllMess();
        for(int i=0;i<=employees.size()-1;i++){
            Employee employee = employees.get(i);
            //创建行
            row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }

        /*
        //创建列，实际就是创建单元格
        Cell cell = row.createCell(0);
        //设置内容到单元格
        cell.setCellValue("wolfcode");
        */
        return wb;
    }

    //导入
    @Override
    public void importxls(MultipartFile file) throws IOException {
//        System.out.println("file======"+file);
        //读取接收到的模板文件xls 并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
//        System.out.println("wb======"+wb);
        //读取sheet
        Sheet sheet = wb.getSheetAt(0);
//        System.out.println("sheet======"+sheet);
        //先获取总行数(索引号),索引从0开会时
        int rows = sheet.getLastRowNum();
//        System.out.println("rows======"+rows);
        //从索引为1的行数开始取数。循环要从1开始
        for (int i=1;i<=rows;i++){
            //在循环里获取每行的内容。
            Row row = sheet.getRow(i);
//            System.out.println("row======"+row);
            Employee employee = new Employee();
            //getXXXCellCalue()要与XLS 单元格的类型保持一致
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            employee.setAge((int) row.getCell(2).getNumericCellValue());
//            System.out.println("employee======"+employee);
//            System.out.println("-----------------------");
//            Md5Hash md5 = new Md5Hash(row.getCell(0).getStringCellValue(),employee.getName());
            employee.setPassword("1");
            //保存到数据库
            this.saveOrUpdate(employee,null);
//            System.out.println("emp==== "+employee);
        }
    }
}
